package top.yqingyu.trans$client.main;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yqingyu.common.utils.ClazzUtil;
import top.yqingyu.qymsg.MsgHelper;
import top.yqingyu.qymsg.MsgType;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.trans$client.api.Connection;
import top.yqingyu.trans$client.cs.command.Command;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.transclient.sc.thread.DealMsgThread
 * @description
 * @createTime 2022年07月23日 18:06:00
 */
public record DealMsgThread(QyMsg msgHeader, Connection conn, TransClient client) implements Runnable {

    private final static Logger logger = LoggerFactory.getLogger(DealMsgThread.class);
    private static final HashMap<String, Command> Reg_Class = new HashMap<>();

    @Override
    public void run() {
        logger.debug("DEAL> {}", JSON.toJSONString(msgHeader));
        AtomicReference<Command> a = new AtomicReference<>();
        try {

            if (Reg_Class.isEmpty()) {
                try {
                    List<Class<?>> classList = ClazzUtil.getClassList("top.yqingyu.trans$client.cs.command.impl", false);

                    for (Class<?> clazz : classList) {
                        Field field = clazz.getDeclaredField("commandRegx");
                        field.setAccessible(true);
                        String o = (String) field.get((Object) null);
                        Reg_Class.put(o, (Command) clazz.getDeclaredConstructor().newInstance());
                    }
                } catch (IllegalAccessException | NoSuchFieldException e) {
                    logger.error("", e);
                }
            }

            Reg_Class.forEach((regx, clazzx) -> {
                if (MsgHelper.gainMsg(msgHeader).matches(regx)) {
                    a.set(clazzx);
                }
            });
        } catch (Exception e) {
            logger.error("命令处理异常", e);
        }
        try {
            if (a.get() != null && (msgHeader.getMsgType() != MsgType.HEART_BEAT)) {
                Command o = a.get();
                o.dealCommand(client, conn, msgHeader);
                logger.info("调用类: {}", o.getClass().getSimpleName());
            } else {
                conn.send(msgHeader);
            }
        } catch (Exception e) {
            logger.error("命令处理异常", e);
            throw new RuntimeException(e);
        }
    }
}
